package com.scpii.universal.service.impl;

import java.util.LinkedList;

public class WorkQueue {
	private final int threadNum;
	private final PoolWorker[] workThread;
	private final LinkedList<Runnable> queue;//任务队列
	
	public WorkQueue(int size) {
		this.threadNum = size;
		queue = new LinkedList<Runnable>();
		workThread = new PoolWorker[threadNum];
		for (int i = 0; i < threadNum; i++) {
			workThread[i] = new PoolWorker();
			workThread[i].start();//启动工作线程
		}
	}
	
	public void execute(Runnable r) {
		synchronized (queue) {
			queue.addLast(r);
			queue.notify();
		}
	}
	
	//工作线程类
	private class PoolWorker extends Thread {

		@Override
		public void run() {
			Runnable r;
			while(true){
				synchronized (queue) {
					while(queue.isEmpty()){
						try {
							queue.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					r = (Runnable) queue.removeFirst();
					r.run();
				}
			}
		}
		
	}
}
